from machine import PWM,Pin
import socket
import time
import network
import machine

#连接热点
def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('meik30s', '5201314ygyu')  #配置热点名称和密码
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            time.sleep(1)
    print('network config:', wlan.ifconfig())


#配置UDP接受初始化
def start_udp():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(("192.168.196.56", 7788))
    return udp_socket

#用于蜂鸣器的警报发声
def buzzer_sound(alerts):
    # 处理接收的数据,开启蜂鸣器警报
    buzzer = PWM(Pin(25))
    if alerts == "1":
        print("蜂鸣器响!!")
        buzzer.freq(1000)
        buzzer.duty(250)
        
    elif alerts == "0":
        print("蜂鸣器不响!!")
        buzzer.duty(0)

#用于调用各个模块
def buzzer_alert():
    #do_connect()
    udp_socket = start_udp()
    # 接收网络数据
    while True:
        recv_data, sender_info = udp_socket.recvfrom(1024)
        print("{}发送{}".format(sender_info, recv_data))
        recv_data_alerts = recv_data.decode("utf-8")
        buzzer_sound(recv_data_alerts)



if __name__ == "__main__":
    buzzer_alert()

